Online-Academy
Look, Read, Understand, Apply

Data Structure

Copy Linked List to array

A simple linked list is creating in the following program. Node class with data field and address field is defined, constructor is defined to set value for data field (second constructor), show method returns content of a node.

In the driver class (class with main method): while loop is used to create a linked list, numbers from 100 to 109 is stored in the list.

A third loop (for loop) is created to loop through the list, as the fourth position is reached loop is stopped. temp1 iterates through the list and stops at the fourth node (i != 3); A new node temp2 is created; in next field of temp2 reference of 5th node (temp1.next) is stored, then in next field of 4th node (temp1.next), temp2 is stored. A node is inserted in the list.

The list traversed in the fifth loop (for loop), and data of list is stored in the array arr.

class node{
    int data;
    node next;
    public node(){
        next = null;
    }
    public node(int d){
        data = d;
        next = null;
    }
    public int show(){
        //System.out.println(" "+data);
        return data;
    }
}

class linkedlist_demo{
    public static void main(String[] ar){
        node head = null, temp1,temp2=null;
        int i=100;
        int aar[] = new int [20],j=0;
        //creating linked list wiht 10 elements;
        while(i<110){
            temp1 = new node(i);
            if(head == null){
                head = temp1;
                temp2 = temp1;
                //head.show();
            }else{
                temp2.next = temp1;
                temp2 = temp1; 
                //temp2.show();
            }
            ++i;
        }
        //display list
        System.out.println("\nBefore inserting new node:--->");
        for(temp1 = head;temp1!=null;temp1=temp1.next){
            System.out.print(" "+ temp1.show());
        }

        //inserting new node after given position, 
        //here new node will be inserted after 4th node
        i=0;
        for(temp1 = head;i!=3;temp1=temp1.next){
            i++;
        }
        temp2 = new node(9999);
        temp2.next = temp1.next;
        temp1.next = temp2;
        

        System.out.println("\nAfter inserting new node:--->");
        for(temp1 = head;temp1!=null;temp1=temp1.next){
            System.out.print(" "+ temp1.show());
        }

        //coping contents of linked list to array
        j=0;
        for(temp1 = head;temp1!=null;temp1=temp1.next){
            aar[j++] = temp1.show();
        }
        //Displaying content of array
        System.out.println("\nPrinting content of array--> ");
        for(i=0;i<j;i++)
        System.out.print(" "+aar[i]);
    }
}
Output:
Before inserting new node:--->
 100 101 102 103 104 105 106 107 108 109
After inserting new node:--->
 100 101 102 103 9999 104 105 106 107 108 109
Printing content of array-->
 100 101 102 103 9999 104 105 106 107 108 109